<?php
if (!isset($_SESSION)) session_start();
include "functions.php";
include "constants.php";

$token = $_POST['token'];
if(!$token) exit(0);

$graphApiUser = 'https://graph.facebook.com/me?access_token='.$token;
$response = cURL($graphApiUser);
if($response){
	$userData = json_decode($response, true);
	if(!empty($userData) && $userData['id']){
		if($userData['gender'] == 'male' || $userData['gender'] == 'female' ){
			$gender = strtoupper($userData['gender']);
		}
		else{
			$gender = '';
		}
		$params = array(
			'user_social_id'	=>	$userData['id'],
			'user_email'		=>	$userData['email'],
			'user_fullname'		=>	$userData['name'],
			'user_sso'			=>	'FACEBOOK',
			'user_gender'		=>	$gender,
			'user_sso_rawdata'	=>	mysql_real_escape_string(json_encode($userData))
		);
		$sqlInsert = sqlInsertString($params, 'users');
		$i = 1;
		$sep = "";
		$sqlUpdate = "";
		$count = count($params);
		foreach($params as $field => $value){
			if($i < $count){
				$sep = ', ';
			}
			else{
				$sep = '';
			}
			$sqlUpdate .= "`$field` = '$value'".$sep;
			
			$i++;
		}
		$sqlInsert = $sqlInsert . " ON DUPLICATE KEY UPDATE " . $sqlUpdate;

		if(mysql_query($sqlInsert)){
			$sqlInfo = "SELECT user_id, user_fullname FROM users WHERE user_social_id='".$params['user_social_id']."'";
			$query = mysql_query($sqlInfo);
			$userInfo = mysql_fetch_array($query);

			$_SESSION['user'] = array(
				'id'	=>	$userInfo['user_id'],
				'name'	=>	$userInfo['user_fullname'],
				);
			$_SESSION['sso'] = 'FACEBOOK';
			$_SESSION['token'] = $token;
			echo '1';
		}
		else{
			echo '0';
		}
	}
}
die;